<?php

namespace app\storeapi\controller\market;

use app\storeapi\controller\Controller;
use app\storeapi\model\Coupon as CouponModel;
use app\storeapi\model\UserCoupon as UserCouponModel;

/**
 * 优惠券管理
 * Class Coupon
 * @package app\store\controller\market
 */
class Coupon extends Controller
{


    /**
     * 优惠券列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $model = new CouponModel;
        $param = $this->postData();
        $list = $model->getList($param);
        return $this->renderSuccess($list);
    }

    /**
     * 添加优惠券
     * @return array|mixed
     */
    public function add()
    {
        $model = new CouponModel;
        $param = $this->postData();
        // 新增记录
        if ($model->add($param)) {
            return $this->renderSuccess([],'添加成功');
        }
        return $this->renderError('添加失败');
    }


    /**
     * 优惠券详情
     * @param $coupon_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function info()
    {
        $param = $this->postData();
        $coupon_id = $param['coupon_id'];
        // 优惠券详情
        $model = CouponModel::detail($coupon_id)?:[];
        return $this->renderSuccess($model);
    }


    /**
     * 更新优惠券
     * @param $coupon_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $param = $this->postData();
        $coupon_id = $param['coupon_id'];
        // 优惠券详情
        $model = CouponModel::detail($coupon_id);
        if(!$model){
            return $this->renderError('优惠券不存在,请刷新后重试');
        }
        // 更新记录
        if ($model->edit($param)) {
            return $this->renderSuccess([],'更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除优惠券
     * @param $coupon_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function delete()
    {
        $param = $this->postData();
        $coupon_id = $param['coupon_id'];
        // 优惠券详情
        $model = CouponModel::detail($coupon_id);
        if(!$model){
            return $this->renderError('优惠券不存在,请刷新后重试');
        }
        // 更新记录
        if ($model->setDelete()) {
            return $this->renderSuccess([],'删除成功');
        }
        return $this->renderError($model->getError() ?: '删除失败');
    }

    /**
     * 领取记录
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function receive()
    {
        $param = $this->postData();
        $model = new UserCouponModel;
        $list = $model->getUserList($param);
        return $this->renderSuccess($list);

    }

}